<template>
  <div class="padding">
    <el-card>
      <div slot="header" class="flex align-center justify-between">
        <span class="title-icon">文件列表</span>
      </div>
      <el-table
        size="mini"
        :data="fileList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column
          type="index"
          width="44"
          label="序号"
          align="center"
        ></el-table-column>
        <el-table-column prop="fileName" label="文件名" min-width="150">
          <template slot-scope="scope">
            {{ scope.row["fileName"] }}
          </template>
        </el-table-column>

        <el-table-column label="操作">
          <template slot-scope="scope">
            <i
              style="color:green;"
              class="el-icon-view text-xl margin-right-sm"
              @click="previewFile(scope.$index, scope.row)"
            ></i>
            <i
              class="el-icon-edit pointer text-xl"
              @click="onEditFile(scope)"
            ></i>
            <i
              v-if="verifyShow.downloadFile"
              class="el-icon-download pointer margin-lr-sm text-xl"
              @click="onDownLoad(scope)"
            ></i>
            <i
              v-if="verifyShow.deleteFile"
              class="el-icon-delete pointer text-xl"
              @click="onDel(scope)"
            ></i>
          </template>
        </el-table-column>

        <el-table-column prop="fileTypeId" label="文件类型">
          <template slot-scope="scope">
            {{ fileTypeMap[scope.row["fileTypeId"]] }}
          </template>
        </el-table-column>

        <el-table-column
          prop="remark"
          label="备注"
          min-width="200"
          :fit-header="true"
          :auto-fit="true"
          show-overflow-tooltip
        >
          <!-- <template slot-scope="scope">
            <div class="text-cut">
              {{ scope.row["remark"] }}
            </div>
          </template> -->
        </el-table-column>
        <el-table-column prop="isPush" label="是否已推送">
          <template slot-scope="scope">
            {{ scope.row["isPush"] ? "是" : "否" }}
          </template>
        </el-table-column>
        <el-table-column prop="cuser" label="创建人">
          <template slot-scope="scope">
            {{ userAll[scope.row["cuser"]] }}
          </template>
        </el-table-column>
        <el-table-column prop="cdate" label="创建时间"></el-table-column>
      </el-table>

      <div class="padding-top">
        <el-button
          v-if="verifyShow.uploadFile"
          size="mini"
          type="primary"
          @click="showUpload"
        >
          上传文件
        </el-button>
        <el-button
          v-if="verifyShow.downloadFile"
          size="mini"
          type="success"
          @click="batchDownLoad"
        >
          批量下载文件
        </el-button>
        <el-button size="mini" type="success">发送邮件</el-button>
      </div>
    </el-card>

    <el-dialog :visible.sync="uploadDialog" width="40%">
      <el-form
        :model="uploadForm"
        :rules="rules"
        ref="uploadForm"
        label-width="100px"
      >
        <el-form-item label="类型" prop="fileTypeId">
          <el-select
            v-model="uploadForm.fileTypeId"
            filterable
            placeholder="请选择类型"
          >
            <el-option
              v-for="(item, value) in fileTypeMap"
              :key="value"
              :label="item"
              :value="parseInt(value)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="文件名称" prop="fileName">
          <el-input v-model="uploadForm.fileName"></el-input>
        </el-form-item>
      </el-form>

      <el-upload
        class="upload-demo"
        drag
        ref="upload"
        action="#"
        :limit="1"
        :auto-upload="true"
        :file-list="uploadFileList"
        :http-request="uploadFn"
        :on-change="onChange"
      >
        <i class="el-icon-upload" />
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <!-- <div slot="tip" class="el-upload__tip" v-if="fileType">
          只能上传{{
            fileType === "img" ? "jpg/png" : "excel"
          }}文件，且不超过5MB
        </div> -->
        <!-- <el-button slot="trigger" size="small" type="primary">选取文件</el-button> -->
      </el-upload>
      <span slot="footer" class="dialog-footer">
        <el-button @click="uploadDialog = false">取 消</el-button>
        <el-button type="primary" @click="submitUpload">保存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { ajax } from "@/store/yg/common/utils";
import axios from "axios";
import { untransform } from "@/store/yg/common/uri";
import * as constant from "@/store/yg/common/constant";
export default {
  props: {
    verifyShow: {
      type: Object,
      default: function() {
        return {};
      }
    },
    waybillId: {
      type: Number,
      default: 1
    },
    fileTypeMap: {
      type: Object,
      default: function() {
        return {};
      }
    },
    userAll: {
      type: Object,
      default: function() {
        return {};
      }
    },
    activeName: {
      type: String
    },
    shippingWay: {
      type: String
    }
  },
  watch: {
    fileTypeMap(newValue, oldValue) {
      console.log("newValuefileTypeMap :>> ", newValue);
    }
  },
  data() {
    return {
      uploadFileList: [],
      uploadForm: {
        fileName: "",
        fileTypeId: "",
        fileUrl: "",
        fileTypeName: ""
      },
      rules: {
        fileTypeId: [
          { required: true, message: "请选择文件类型", trigger: "change" }
        ],
        fileName: [
          { required: true, message: "请填写文件名称", trigger: "blur" }
        ]
      },
      uploadDialog: false,
      multipleSelection: [],
      fileList: []
    };
  },
  mounted() {
    this.init();
  },
  methods: {
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    async init() {
      const data2 = await ajax("queryWaybillFileList", {
        waybillId: this.waybillId
      });
      this.fileList = data2;
    },
    async submitUpload() {
      this.$refs["uploadForm"].validate(valid => {
        if (!valid) {
          return false;
        }
      });
      if (!this.uploadForm.fileUrl) {
        this.$message.error("请上传文件！");
        return;
      }
      this.uploadForm.waybillId = this.waybillId;
      this.uploadForm.fileTypeName = this.fileTypeMap[
        this.uploadForm.fileTypeId
      ];

      const { code, message } = await ajax(
        "createOrUpdateWaybillFile",
        this.uploadForm
      );
      if (code === 200) {
        this.$message({
          type: "success",
          message: "上传成功"
        });
        this.uploadDialog = false;
        this.init();
      } else {
        this.$message.error(message);
      }
    },
    async onDel(params) {
      this.$confirm("确认删除文件？")
        .then(_ => {
          ajax("deleteWaybillFile", {
            id: params.row.id
          }).then(res => {
            if (res.code === 200) {
              this.$message({
                type: "success",
                message: "已删除！"
              });
              this.init();
            } else {
              this.$message.error("删除失败！" + res.message);
            }
          });
        })
        .catch(_ => {});
    },
    async batchDownLoad() {
      const data = await ajax("batchDownLoadWaybillFile", {
        waybillId: this.waybillId,
        shippingWay: this.shippingWay
      });

      window.open(data.path);
    },
    async onDownLoad(params) {
      var fileName = params.row.fileUrl;
      var name = params.row.fileName;
      var uploadpath = "/";
      console.log(fileName);
      var path = (path = constant.FILE_SERVER + uploadpath);
      var fileUrl = path + fileName;

      location.href =
        constant.API_SERVER +
        "/open/downloadFileByHttp?fileName=" +
        name +
        "&path=" +
        fileUrl;

      // window.open(constant.FILE_SERVER + params.row.fileUrl);
    },
    async uploadFn(params) {
      const formData = new FormData();
      formData.append("items[]", params.file);
      formData.append("waybillId", this.waybillId);
      const action =
        constant.API_SERVER +
        "/api/consume/upload?uri=" +
        untransform(this.$route.params.uri) +
        "&f=uploadAbroadWaybillFile&type=blank";
      axios({
        url: action,
        method: "post",
        data: formData,
        headers: {
          "Content-Type": "multipart/form-data"
        }
      }).then(res => {
        console.log("res :>> ", res);
        if (res.data.fileUrl) {
          this.uploadForm.fileUrl = res.data.fileUrl;
          this.uploadForm.fileName = res.data.fileName;
        } else {
          this.$message.error(res.data.message);
        }
      });
    },
    onChange() {},
    async onEditFile(params) {
      console.log("params :>> ", params);
      const data = await ajax("findWaybillFileById", {
        id: params.row.id
      });

      this.uploadForm = data;
      this.uploadDialog = true;
    },
    previewFile(index, row) {
      console.log(row);
      var param = {};

      var fileName = row.fileUrl;
      param["fileName"] = fileName;
      var name = row.fileName;
      var uploadpath = "/";
      console.log(fileName);
      var path = (path = constant.FILE_SERVER + uploadpath);
      var fileUrl = path + fileName;
      // var url = "/#/view/viewWaybillFile?fileUrl=" + fileUrl;
      var fileExt = /[.]/.exec(fileName)
        ? /[^.]+$/.exec(fileName.toLowerCase())
        : ""; // 文件扩展名
      console.log("names", fileExt);
      if (
        fileExt == "pdf" ||
        fileExt == "jpg" ||
        fileExt == "tif" ||
        fileExt == "bmp" ||
        fileExt == "gif" ||
        fileExt == "png" ||
        fileExt == "jpeg"
      ) {
        window.open(fileUrl, "_blank");
      } else if (
        fileExt == "doc" ||
        fileExt == "docx" ||
        fileExt == "xlsx" ||
        fileExt == "xls" ||
        fileExt == "pptx" ||
        fileExt == "ppt"
      ) {
        ajax("filePreviewByServer", param).then(
          res => {
            if (res.code != 200) {
            } else {
              window.open(res.data);
            }
          },
          error => {
            console.log(error);
          }
        );
      }
    },
    showUpload() {
      this.uploadFileList = [];
      this.uploadDialog = true;
    }
  }
};
</script>

<style scoped>
/deep/ .el-select {
  width: 100%;
}
</style>
